from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin
# Create your views here.

from .models import Areas
from .serializers import AreasSerializer, SubsAreasSerializer


# GET /areas/
# GET /areas/(?P<pk>\d+)/
# 提供省市区三级联动的数据
class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):

    #禁用分页
    pagination_class = None

    # 指定数据来自哪个模型类, 根据不同的请求行为，返回不同的数据
    def get_queryset(self):
        if self.action == 'list':
            return Areas.objects.filter(parent=None)# parent=None表示的是省级数据， 没有父级
        else:
            return Areas.objects.all()


    # 指定序列化器， 根据请求的不同选择不同的序列化器
    def get_serializer_class(self):
        if self.action == 'list':
            return AreasSerializer
        else:
            return SubsAreasSerializer
